{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ce5e76a5-222b-408d-b90c-19a801432e66",
   "metadata": {},
   "source": [
    "# LangChain 核心模块 Agent - ReAct\n",
    "\n",
    "ReAct 核心思想是 推理+操作，本示例以` Google Search` 和 `LLM Math` 作为可选操作集合（toolkits），实现 ReAct 功能。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cd59da96-dda8-42c8-9c82-8460cf3aa75d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# 更换为自己的 Serp API KEY\n",
    "os.environ[\"SERPAPI_API_KEY\"] = \"1e3c93e0753ac224098370cd71da86150c6609caba6b5aaa307e04b72a5006e1\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d03a5086-d453-44f2-898b-0fecb746d0c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.llms import OpenAI\n",
    "\n",
    "llm = OpenAI(temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9e7e7202-625a-4cec-999a-321a40115792",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import load_tools\n",
    "from langchain.agents import initialize_agent\n",
    "from langchain.agents import AgentType\n",
    "\n",
    "#加载 LangChain 内置的 Tools\n",
    "tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d89d569f-5313-42f3-8f1a-ea45fb1ea035",
   "metadata": {},
   "source": [
    "### 使用语言模型（GPT-3）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "70af3538-18c4-4c64-99a7-96b32038d31b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 实例化 ZERO_SHOT_REACT Agent\n",
    "agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "484bba88-885b-4630-a9a9-b2ff6241df83",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m I need to find out who Leonardo DiCaprio's girlfriend is and then calculate her age to the 0.43 power.\n",
      "Action: Search\n",
      "Action Input: \"Leonardo DiCaprio girlfriend\"\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m[{'title': 'Leo in Paris with nine ex-girlfriends', 'link': 'https://www.news.com.au/entertainment/celebrity-life/celebrity-photos/leonardo-dicaprios-nine-exgirlfriends-at-paris-fashion-week/news-story/bd07623139cbc42f9ad683c72ab8609a', 'source': 'News.com.au', 'date': '3 days ago', 'thumbnail': 'https://serpapi.com/searches/652119a3b5961e6fd63885e9/images/7db95bf161919ea5f1437993aeba4501fe9fba0acebd51c0.jpeg'}, {'title': \"Leonardo DiCaprio in Paris at same time as 'new girlfriend and nine other exes'\", 'link': 'https://www.dailystar.co.uk/showbiz/us-showbiz/leonardo-dicaprio-paris-same-time-31105443', 'source': 'The Daily Star', 'date': '2 days ago', 'thumbnail': 'https://serpapi.com/searches/652119a3b5961e6fd63885e9/images/7db95bf161919ea5cc24078b67e8880b2a2065d86299c6fa.jpeg'}, {'title': 'Leonardo DiCaprio and new girlfriend Vittoria Ceretti grab dinner with friends in Paris', 'link': 'https://pagesix.com/2023/09/27/leonardo-dicaprio-girlfriend-vittoria-ceretti-grab-dinner-in-paris/', 'source': 'Page Six', 'date': '1 week ago', 'thumbnail': 'https://serpapi.com/searches/652119a3b5961e6fd63885e9/images/7db95bf161919ea541824bea9924d255b388ee4b94430297.jpeg'}, {'title': 'EXCLUSIVE: Leonardo DiCaprio, 48, settles down with Italian model girlfriend Vittoria Ceretti, 25, as pals cla', 'link': 'https://www.dailymail.co.uk/tvshowbiz/article-12491855/Leonardo-DiCaprio-settles-Italian-model-Vittoria-Ceretti-25-besotted-new-flame.html', 'source': 'Daily Mail', 'date': '1 month ago', 'thumbnail': 'https://serpapi.com/searches/652119a3b5961e6fd63885e9/images/7db95bf161919ea53904a654108da52820108789c1eba021.jpeg'}]\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m Leonardo DiCaprio's girlfriend is Vittoria Ceretti.\n",
      "Action: Calculator\n",
      "Action Input: 25^0.43\u001b[0m\n",
      "Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.991298452658078\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
      "Final Answer: Vittoria Ceretti的年龄的0.43次方是3.991298452658078。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Vittoria Ceretti的年龄的0.43次方是3.991298452658078。'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.run(\"谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b816038d-6f3a-47cb-b614-e432db8c1883",
   "metadata": {},
   "source": [
    "### 使用聊天模型（GPT-4）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "448c877f-577b-4277-a155-51223dc3d949",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mThought: This question has two parts. First, I need to find out who Leonardo DiCaprio's girlfriend is. Then, I need to find out her age and calculate her age to the power of 0.43. I will start by searching for Leonardo DiCaprio's girlfriend. \n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"Search\",\n",
      "  \"action_input\": \"Leonardo DiCaprio's girlfriend\"\n",
      "}\n",
      "```\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3mBut after years of canoodling with various much younger beautiful women, Leonardo DiCaprio has finally settled down - at the age of 48. The Mail can reveal that the Hollywood actor has been dating Italian model Vittoria Ceretti for at least two months after they were seen kissing in an Ibiza nightclub this week.\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mLeonardo DiCaprio's girlfriend is Vittoria Ceretti. Now I need to find out her age. \n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"Search\",\n",
      "  \"action_input\": \"Vittoria Ceretti age\"\n",
      "}\n",
      "```\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m25 years\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mVittoria Ceretti is 25 years old. Now I need to calculate 25 to the power of 0.43.\n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"Calculator\",\n",
      "  \"action_input\": \"25**0.43\"\n",
      "}\n",
      "```\u001b[0m\n",
      "Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.991298452658078\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mThe age of Vittoria Ceretti to the power of 0.43 is approximately 3.99.\n",
      "Final Answer: 莱昂纳多·迪卡普里奥的女朋友是Vittoria Ceretti，她的年龄的0.43次方是3.99。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'莱昂纳多·迪卡普里奥的女朋友是Vittoria Ceretti，她的年龄的0.43次方是3.99。'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4\", temperature=0)\n",
    "agent = initialize_agent(tools, chat_model, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",
    "agent.run(\"谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67f4728e-bf1f-4643-a2ee-8f8679ddc58a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
